import { Component, Prop, Watch } from 'vue-property-decorator';

import {
  RequestParams,
  ResponseSuccess,
  ResponseFail,
  ObjectValue,
  ListValue,
  noop,
} from '../../vendors/handie';
import { DynamicRelationField } from '../../vendors/handie/types/input';

import FieldHeadlessWidget from './Field';

@Component
export default class RelationFieldHeadlessWidget<
  ValueType = ObjectValue | ListValue
> extends FieldHeadlessWidget<ValueType> {
  @Prop({ type: [Object, Array], default: null })
  protected readonly value!: ValueType;

  protected internalValue: ValueType = null as any;

  protected get labelKey(): string {
    return (this.field.dynamic && (this.field as DynamicRelationField).relatedLabelKey) || 'label';
  }

  protected get valueKey(): string {
    let key = 'value';

    if (this.field.dynamic) {
      key =
        (this.field as DynamicRelationField).relatedValueKey ||
        (this.field as DynamicRelationField).relatedPrimaryKey ||
        key;
    }

    return key;
  }

  @Watch('value', { immediate: true })
  private handleValueChange(): void {
    if (!this.field.dynamic || !(this.field as DynamicRelationField).referenceValueGetter) {
      this.internalValue = this.value;
    }
  }

  private fetchReferenceValue(data: ValueType): void {
    const { referenceValueGetter } = this.field as DynamicRelationField;

    if (!referenceValueGetter) {
      return;
    }

    referenceValueGetter(data).then(result => {
      if (result.success) {
        this.internalValue = result.data;
      }
    });
  }

  protected fetchRelatedList(
    params: RequestParams,
    success: ResponseSuccess = noop,
    fail: ResponseFail = noop,
  ): void {
    const { dynamic, relatedListGetter } = this.field as DynamicRelationField;

    if (!dynamic || !relatedListGetter) {
      return;
    }

    relatedListGetter(params).then(result => {
      if (result.success) {
        success(result.data, result.extra, result);
      } else {
        fail(result.message, result);
      }
    });
  }

  protected created(): void {
    if (this.field.dynamic) {
      this.on('dataChange', dataSource => this.fetchReferenceValue(dataSource));
    }
  }
}
